﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using FinalCountdownServices.Models;
using Microsoft.Phone.Shell;

namespace FinalCountdownServices
{
    public interface ITileService
    {
        void AddOrModifyTileByEvent(EventModel e);
        void RemoveTileById(int eventId);
        void UpdateAllAndReSchedule(List<EventModel> myEvents);
    }

    public class TileService : ITileService
    {
        public void AddOrModifyTileByEvent(EventModel e)
        {
            var tile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("EventId=" + e.Id));

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {

                var imgUri = new Uri("isostore:/Shared/ShellContent/FinalCountdownBg_tmp_" + e.Id + ".jpg",
                                     UriKind.Absolute);
                var logo = new BitmapImage(imgUri);
                var img = new Image { Source = logo };

                var bmp = new WriteableBitmap(173, 173);
                var bl = new TextBlock();
                bl.Foreground = new SolidColorBrush(Colors.White);
                bl.FontSize = 24.0;
                bl.Text = "Hátravan: \n" + e.RemainingDays + " nap, " + e.RemainingHours + " óra";
                bmp.Render(bl, null);

                var tt = new TranslateTransform();
                tt.X = 173 - logo.PixelWidth;
                tt.Y = 173 - logo.PixelHeight;
                bmp.Render(img, tt);

                bmp.Invalidate();

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    var filename = "/Shared/ShellContent/FinalCountdownBg_" + e.Id + ".jpg";
                    using (var st = new IsolatedStorageFileStream(filename, FileMode.Create, FileAccess.Write, store))
                    {
                        bmp.SaveJpeg(st, 173, 173, 0, 100);
                    }
                }

            });

            var eventTile = new StandardTileData
                                {
                                    Title = e.Title,
                                    BackgroundImage = new Uri("isostore:/Shared/ShellContent/FinalCountdownBg_" + e.Id + ".jpg", UriKind.Absolute),
                                    BackBackgroundImage = e.BackgroundSource,
                                    BackTitle = e.Title,
                                    BackContent = e.Description
                                };

            if (tile != null)
            {
                tile.Update(eventTile);

            }
            else
            {
                ShellTile.Create(new Uri("/Views/EventPage.xaml?EventId=" + e.Id, UriKind.Relative), eventTile);
            }

            //});



        }
        public void RemoveTileById(int eventId)
        {
            var tile = ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("EventId=" + eventId));
            if (tile != null) tile.Delete();
        }

        public void UpdateAllAndReSchedule(List<EventModel> events)
        {
            foreach (var e in events)
            {
                AddOrModifyTileByEvent(e);

                var tile =
                    ShellTile.ActiveTiles.FirstOrDefault(x => x.NavigationUri.ToString().Contains("EventId=" + e.Id));
                var sc = new ShellTileSchedule(tile);
                sc.Recurrence = UpdateRecurrence.Interval;
                sc.Interval = UpdateInterval.EveryHour;
                sc.StartTime = DateTime.Now;
                sc.RemoteImageUri = new Uri(@"http://www.weather.gov/forecasts/graphical/images/conus/MaxT1_conus.png");
                sc.Start();
            }
        }

    }
}
